﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using AbstractBugTracker;
using SmartAssembly;
using Utilities;

namespace Engine.Buggets
{
    /// <summary>
    /// Sends an email if appropriate
    /// AutoSorry
    /// </summary>
    internal sealed class Spammer<TBug> : IBugget<TBug>
        where TBug : class, IBug
    {
        private readonly IEmailSender m_EmailSender;
        private readonly IDictionary<string, string> m_Templates;

        internal Spammer(IEmailSender emailSender, IDictionary<string, string> templates)
        {
            m_EmailSender = emailSender;
            m_Templates = templates;
        }

        public IEnumerable<Tuple<ProcessedReport, TBug>> Run(ProcessedReport processedReport, TBug bug)
        {
            string userEmail = processedReport.Report.GetCustomProperty("Email");
            if (userEmail != null)
            {
                try
                {
                    // The automatic email field is in this format:
                    // First line = from address
                    // Second line = subject
                    // Other lines = body
                    string automaticEmailField = bug.AutomaticEmail;
                    if (automaticEmailField != null)
                    {
                        // Replace any templates in the message
                        Match m;
                        while ((m = Regex.Match(automaticEmailField, "#(.+?)#")).Success)
                        {
                            string templateName = m.Groups[1].Value;
                            string replaceText = templateName == "BUGREF" ? bug.Key : m_Templates[templateName];
                            automaticEmailField = automaticEmailField.Replace(m.Value, replaceText);
                        }

                        string[] lines = automaticEmailField.Split('\n');
                        if (lines.Length >= 3)
                        {
                            string from = lines[0];
                            string subject = lines[1];
                            string body = string.Join("\n", lines, 2, lines.Length - 2);

                            m_EmailSender.Send(from, userEmail, subject, body);

                            bug.AddComment("Email sent successfully to " + userEmail, false);
                        }
                    }
                }
                catch (Exception e)
                {
                    // Probably an invalid email address
                    bug.AddComment("Exception while trying to send email to " + userEmail + "\n" + e, false);
                }
            }

            yield return new Tuple<ProcessedReport, TBug>(processedReport, bug);
        }
    }
}
